//
//  WJMEVC.m
//  WJBSApp
//
//  Created by dllo on 16/7/17.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJMEVC.h"
#import "WJ_TJDY_VC.h"    // 推荐订阅界面
#import "WJ_MeFollow_VC.h"  //我的关注 界面
#import "WJ_Me_Search_VC.h"  //搜索界面
#import "WJMeCell.h"
#import "WJMeModel.h"
#import "SDImageCache.h"  //图片缓存 清除
#import "UIImage+WJResize.h"  //切图片的方法  不会用
#import "WJ_Me_Lable.h"  // 两条Lable
#import "WJEssAndNewLable.h"
#import "WJDataManager.h"
#import "SVProgressHUD.h"

@interface WJMEVC ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain) WJBaseTableView *tableView;

@property (nonatomic,retain) WJBaseImageView *headerImageView;

@property (nonatomic,retain) WJBaseButton *gzButton;

@property (nonatomic,retain) NSString *gzButtonTitle;

@property (nonatomic,retain) WJBaseButton *hcButton;

@property (nonatomic,retain) WJHotLable *nightLable;

@property (nonatomic,retain) NSMutableArray *firArray;

@property (nonatomic,retain) NSMutableArray *secArray;

@property (nonatomic,retain) MBProgressHUD *hub;


@end

@implementation WJMEVC

static NSString *const WJMECell = @"WJMECell";

-(void)dealloc
{
    [_tableView release];
    [_headerImageView release];
    [_gzButton release];
    [_gzButtonTitle release];
    [_hcButton release];
    [_nightLable release];
    
    [_firArray release];
    [_secArray release];
    [_hub release];
    
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    [super dealloc];
}

//每次进来都要执行
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
    
#pragma mark - 在程序第一次进入这个页面的时候firArray是没有值的  所以无法判断 所以应该在程序第二次进入这个页面的时候我们才可以添加这个值
    
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"LogInMe"] isEqualToString:@"2"]) {

        // 第一个数组的解析
        self.firArray = [[WJDataManager shareFMDB] selectAllFir];
        
        // 第二个数组的解析
        self.secArray = [[WJDataManager shareFMDB] selectAllSec];
        
        [self.tableView reloadData];
        [self.hub hide:YES];
    }else{
    
     [[NSUserDefaults standardUserDefaults] setValue:@"2" forKey:@"LogInMe"];
    
    }
    
}



- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}



// 这个方法值执行一次
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我的";
    
    self.firArray = [NSMutableArray array];
    self.secArray = [NSMutableArray array];
    
    [self creataView];
    
    [self createHeadView];
    
    [self createData];
    
}

#pragma mark - 建立了TableView的头视图
- (void)creataView
{
    self.tableView = [[WJBaseTableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = HEIGHT / 9;
    self.tableView.bounces = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(260, 0, 0, 0);
    [self.tableView registerClass:[WJMeCell class] forCellReuseIdentifier:WJMECell];
    [_tableView release];
    
    self.hub = [[MBProgressHUD alloc]init];
    [self.view addSubview:self.hub];
    [self.hub show:YES];
    [_hub release];
    
}

- (void)createHeadView{
    // 建立头视图
    WJBaseView *view = [[WJBaseView alloc]initWithFrame:CGRectMake(0, -260, WIDTH, 100)];
    [self.tableView addSubview:view];
    [view release];
    
    self.headerImageView = [[WJBaseImageView alloc]initWithFrame:CGRectMake(WIDTH/2 - 50, 0, 100, 100)];
    [view addSubview:self.headerImageView];
    self.headerImageView.layer.cornerRadius = 50;
    self.headerImageView.layer.masksToBounds = YES;
    self.headerImageView.image = [UIImage imageNamed:@"CropTmpFile-1467030948717.jpg"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    self.headerImageView.userInteractionEnabled = YES;
    [self.headerImageView addGestureRecognizer:tap];
    [tap release];

    [_headerImageView release];
    
    // 我的关注
    
    self.gzButton = [WJBaseButton buttonWithTitle:@"我的发表" frame:CGRectMake(0, -160, WIDTH, 50) target:self action:@selector(gzButtonAction:)];
    [self.tableView addSubview:self.gzButton];
    
    //    但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    self.gzButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //    使文字距离做边框保持10个像素的距离。
    self.gzButton.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
    
    // 我的缓存
    
    self.hcButton = [WJBaseButton buttonWithTitle:@"清除缓存" frame:CGRectMake(0, -110, WIDTH, 50) target:self action:@selector(hcButtonAction:)];
    [self.tableView addSubview:self.hcButton];
    //    但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    self.hcButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //    使文字距离做边框保持10个像素的距离。
    self.hcButton.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
    
    UILabel *lable2 = [[UILabel alloc]initWithFrame:CGRectMake(0, -100, WIDTH, 1)];
    [self.tableView addSubview:lable2];
    lable2.backgroundColor =[UIColor lightGrayColor];
    [lable2 release];
    
    // 夜间模式
    
    self.nightLable = [[WJHotLable alloc]initWithFrame:CGRectMake(10, -60, WIDTH - 100, 50)];
    [self.tableView addSubview:self.nightLable];
    [_nightLable release];
    self.nightLable.text = @"夜间模式";
    
    UILabel *lable3 = [[UILabel alloc]initWithFrame:CGRectMake(0, -60, WIDTH, 1)];
    [self.tableView addSubview:lable3];
    lable3.backgroundColor = [UIColor lightGrayColor];
    [lable3 release];
    
    UISwitch *nightSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(WIDTH -90,-50,70,20)];
    [self.tableView addSubview:nightSwitch];
    nightSwitch.tag = 100000;
    nightSwitch.tintColor = [UIColor greenColor];
    nightSwitch.onTintColor = LABLECOLOR;
    [nightSwitch release];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Mode"] isEqualToString:@"night"]) {
        nightSwitch.backgroundColor = FORBLACKCOLOR;
    }else{
        nightSwitch.backgroundColor = LABLECOLOR;
    }
    // 接受通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"changeColor" object:nil];
    //设置状态
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Mode"] isEqualToString:@"night"]) {
        [nightSwitch setOn:YES];
    } else {
        [nightSwitch setOn:NO];
    }
    [nightSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, -10, WIDTH, 1)];
    [self.tableView addSubview:lable];
    lable.backgroundColor = [UIColor lightGrayColor];
    [lable release];
    
    WJ_Me_Lable *belowLable = [[WJ_Me_Lable alloc]initWithFrame:CGRectMake(0, -10, WIDTH, 10)];
    [self.tableView addSubview:belowLable];
    [belowLable release];
    
}


// switch 的夜间模式
- (void)changeColor:(NSNotification *)cation
{
    UISwitch *nightSwitch = [self.tableView viewWithTag:100000];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Mode"] isEqualToString:@"night"]) {
        nightSwitch.backgroundColor = FORBLACKCOLOR;
    }else{
        nightSwitch.backgroundColor = LABLECOLOR;
    }
}



#pragma mark - tableView 的协议方法
// 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.firArray.count;
    }else{
        return self.secArray.count;
    }
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WJMeCell *cell = [tableView dequeueReusableCellWithIdentifier:WJMECell];
    
    cell.dyButton.tag = indexPath.row + 1000;
    [cell.dyButton addTarget:self action:@selector(cellButtonAction:) forControlEvents:1<<6];
    
    // 判断是否是第一分区,第一分区要隐藏
    
    if (indexPath.section == 0) {
        WJMeModel *firmodel = self.firArray[indexPath.row];
        cell.model = firmodel;
        cell.dyButton.hidden = YES;
    }
    if (indexPath.section == 1) {
        WJMeModel *secModel = self.secArray[indexPath.row];
        cell.model = secModel;
        cell.dyButton.hidden = NO;
    }
    
    return cell;
}


// 目前有一个想法因为他是添加之后 重启还存在  可以想到是要存入本地
// 然而并没有什么乱用  还是操作数据吧
#pragma mark ***************************************************写入本地

- (void)cellButtonAction:(WJBaseButton *)button{
    
    WJMeModel *model = self.secArray[button.tag - 1000];
    
    // 将第一个分区添加model
    
    [self.firArray addObject:model];  // add  引用计数加一
    
    // 第二个分区 删除model
    [self.secArray removeObject:model];  //remove 引用计数减一
    
    //进行写入数据库的操作
    
    [[WJDataManager shareFMDB] insertToFirTheme_id:model.theme_id Image_list:model.image_list Sub_number:model.sub_number Post_num:model.post_num Theme_name:model.theme_name];
    
    [[WJDataManager shareFMDB] deleteFromSecTheme_id:model.theme_id];
    
    [self.tableView reloadData];
}





#pragma mark - 点击方法 进入我的订阅
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WJ_TJDY_VC *vc = [[WJ_TJDY_VC alloc]init];
    if (indexPath.section == 0) {
        
        WJMeModel *model = self.firArray[indexPath.row];
        vc.theme_id = model.theme_id;
        vc.title = model.theme_name;

    }
    if (indexPath.section == 1) {
        
        WJMeModel *model = self.secArray[indexPath.row];
        vc.theme_id = model.theme_id;
        vc.title = model.theme_name;
        
    }
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];
    
}


// 分区头部
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"我的订阅";
    }else
        return @"推荐订阅";
}

#pragma mark -   添加订阅
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        WJBaseView *view = [[WJBaseView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT /9 + 10)];
        
        UILabel *uplable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
        [view addSubview:uplable];
        uplable.backgroundColor = [UIColor lightGrayColor];
        [uplable release];
        
        WJBaseImageView *image = [[WJBaseImageView alloc]initWithFrame:CGRectMake(10, 10, HEIGHT / 9 - 20, HEIGHT / 9 - 20)];
        image.image = [UIImage imageNamed:@"98C58PICtVg_1024.jpg"];
        image.layer.cornerRadius = 5;
        image.layer.masksToBounds = YES;
        [view addSubview:image];
        [image release];
        
        WJBaseLable *lable = [[WJBaseLable alloc]initWithFrame:CGRectMake( HEIGHT / 9 , 10, 150, HEIGHT/18 - 10)];
        lable.text = @"添加订阅";
        lable.backgroundColor = [UIColor clearColor];
        lable.font = [UIFont systemFontOfSize:15];
        [view addSubview:lable];
        [lable release];
        
        WJEssAndNewLable *lable1 = [[WJEssAndNewLable alloc]initWithFrame:CGRectMake( HEIGHT / 9 , HEIGHT / 18, 150, HEIGHT/18 - 10)];
        lable1.text = @"添加你喜欢的标签";
        lable1.backgroundColor = [UIColor clearColor];
        lable1.font = [UIFont systemFontOfSize:13];
        [view addSubview:lable1];
        [lable1 release];
        
        UILabel *belowlable = [[UILabel alloc]initWithFrame:CGRectMake(0, HEIGHT /9-1, WIDTH, 1)];
        [view addSubview:belowlable];
        belowlable.backgroundColor = [UIColor lightGrayColor];
        [belowlable release];
        
        UIButton *jumpButton = [UIButton buttonWithTitle:nil frame:CGRectMake(0, 0, WIDTH, HEIGHT/9) target:self action:@selector(jumpBiaoQian:)];
        [view addSubview:jumpButton];
        jumpButton.backgroundColor = [UIColor clearColor];
        
        WJ_Me_Lable *lable3 = [[WJ_Me_Lable alloc]initWithFrame:CGRectMake(0, HEIGHT / 9 , WIDTH, 10)];
        [view addSubview:lable3];
        [lable3 release];
        
        return [view autorelease];
    }
    
    return nil;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return HEIGHT / 9 + 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return HEIGHT / 18;
}


#pragma mark - 跳入搜索按钮
- (void)jumpBiaoQian:(UIButton *)button
{
    WJ_Me_Search_VC *vc = [[WJ_Me_Search_VC alloc]init];
    
    [self.navigationController pushViewController:vc animated:YES];
    
    [vc release];
}

//#warning 啊啊啊啊啊啊啊啊啊啊啊啊将第一个数组写入第一个数据库,将第二个数组写如第二个数据库
- (void)createData
{
    // 如果第一次进入
    
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"哈哈"]) {
        
        [WJNetTool GET:@"http://d.api.budejie.com/tag/subscribe/bs0315-iphone-4.2.json?" body:nil header:nil response:WJJSON success:^(id resuposeObject) {
            
            NSDictionary *dic = resuposeObject;
            NSArray *array = dic[@"rec_tags"];
            
            for (NSDictionary *dic in array) {
                WJMeModel *model = [[WJMeModel alloc]initWithDic:dic];
                [self.secArray addObject:model];
                [[WJDataManager shareFMDB] insertToSecTheme_id:model.theme_id Image_list:model.image_list Sub_number:model.sub_number Post_num:model.post_num Theme_name:model.theme_name];
                [model release];
            }
            [self.tableView reloadData];
            [self.hub hide:YES];
        } failure:^(NSError *error) {
            
            //显示加载失败的信息
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
            [self.hub hide:YES];
        }];
        
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"哈哈"];
        
    } else {
        // 第一个数组的解析
        self.firArray = [[WJDataManager shareFMDB] selectAllFir];
        
        // 第二个数组的解析
        self.secArray = [[WJDataManager shareFMDB] selectAllSec];
        
         [self.tableView reloadData];
        [self.hub hide:YES];
    }
    
    
}


#pragma mark - 进入我的发表
- (void)gzButtonAction:(WJBaseButton *)button
{
    WJ_MeFollow_VC *follow = [[WJ_MeFollow_VC alloc]init];
    [self.navigationController pushViewController:follow animated:YES];
    [follow release];
}


#pragma mark - 清除缓存按钮  现在仅仅清除了图片的缓存 一会要加上 docment文件夹里面的缓存
- (void)hcButtonAction:(WJBaseButton *)button
{
    //获取缓存数据
    NSUInteger size = [[SDImageCache sharedImageCache] getSize];
    //提示
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"缓存为%.02lfM\n 您确定删除吗?", size / 1024.0 / 1024.0] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *acc = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull            action) {
        //清除图片
        if (size != 0) {
            [[SDImageCache sharedImageCache] clearDisk];
            [[WJDataManager shareFMDB]deleteAllPic];
        }
        
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
    
    [alert addAction:acc];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{}];
    
    
}

#pragma mark - switch按钮的动作方法
- (void)switchAction:(UISwitch *)switchBtn{
    if (switchBtn.isOn == YES) {
        //如果是夜间模式
        [[NSUserDefaults standardUserDefaults] setObject:@"night" forKey:@"Mode"];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:@"day" forKey:@"Mode"];
    }
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:nil];
    
}


#pragma mark - 水波纹
- (void)tap:(UITapGestureRecognizer *)tap{
    //
    CATransition *transition = [CATransition animation];
    // 设置动画的类型
    transition.type = @"rippleEffect";
    // 设置动画时长
    transition.duration = 1;
    // 设置重复次数
    transition.repeatCount = 2;
    // 把动画添加到imageView的layer上.
    [self.headerImageView.layer addAnimation:transition forKey:@"transition"];
}























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
